#!/usr/bin/python
import cherrypy
import fdict
from fdict import FDict
from lxml import etree
from kwdict import KWDict
import os
import sys
from urllib import unquote
import pdb
import profile
from stats import Stats
import json
from json import JSONDecoder
from subprocess import Popen
import hashlib

if len(sys.argv) == 1:
    print "Usage: chantag </path/to/images> </path/to/server/root/>"
    exit()
if len(sys.argv) == 2:
    cproot = os.path.realpath("./")
    myimgroot = os.path.join(cproot,sys.argv[1]) 

if len(sys.argv) == 3:
    if os.path.isdir(sys.argv[2]):
        cproot = sys.argv[2]
        myimgroot = os.path.join(sys.argv[2],sys.argv[1])
    else:
        print "Usage: chantag </path/to/images> </path/to/server/root/>"
        print "Invalid image path:" + myimgroot
        exit()
 
if not ( os.path.isfile(myimgroot) or os.path.isdir(myimgroot) ): 
    print "Usage: chantag </path/to/images> </path/to/server/root/>"
    print "Invalid image path:"+ myimgroot
    exit()


cherrypy.config.update({'global':{"tools.staticdir.root":cproot} } )
if len(sys.argv) == 2:
    if os.path.isdir(sys.argv[1]) or os.path.isfile(sys.argv[1]):
        myimgroot=sys.argv[1]   
print ("getting ready!") 
class server:
    def __init__(self):
        self.parsenew = True
        self.fdict  = FDict(myimgroot)
        self.kwdict = self.fdict.kwdict

    def get(self,min,max,**params):
        #pdb.set_trace()
        min,max = int(min),int(max)
        n= int(params.pop("n",0) )
        taglist = []
        while params: taglist.append(params.popitem()[1] )
        print params
        if len(taglist) is 0: taglist.append("new")
        taglist = tuple(taglist) 
        #pdb.set_trace() 
        files = self.kwdict.fileXing(taglist)
        if max == -1: filenames = files[min:]
        else: filenames = files[min:max]
        lst = []
        for filename in filenames:
            lst.append({"num":min,"filename":filename,"tags":self.fdict[filename]})
            min +=1
        return json.dumps([lst,taglist])

   # def tag(self,name,tag):
        #self.fdict[unquote(name)].append(tag)
    def save(self,**jonk):
        #pdb.set_trace()
        for fnum in range(jonk.keys().__len__()):
            changes = json.loads(jonk.keys()[fnum])
        for filename in changes.keys():
            for tag in changes[filename]:
                if tag[0] == '*':
                    self.fdict[filename].append(tag[1:])
                elif tag[0] == '-' and tag[1:] in self.fdict[filename]:
                    self.fdict[filename].remove(tag[1:])
        self.fdict.__groom__()
        self.kwdict = self.fdict.kwdict
    #def deltag(self,imgsrc,tag):
     #   if tag in self.fdict[unquote(imgsrc)]:
     #       self.fdict[imgsrc].remove(tag)
             
    def stats(self):
        popindex = Stats(self.fdict).basics().popu
        statslist =[]
        for tup in popindex:
            try: statslist.append((str(tup[0]),str(tup[1])))
            except: pass
        #cherrypy.response.headers['Content-Type'] = "text/json"
        statslist.sort(key=lambda t:int(t[1]))
        statslist.reverse()
        return json.dumps(statslist[0:50])

    def update(self):
         self.fdict.merge(fdict.FDict(myimgroot))
    def zip(self,**tags):
        tags     = tags.values()
        files    = self.fdict.kwdict.fileXing(tags)
        files.sort()
        filestozip  = "\n".join(files)
        zipfile = "./zip/"+hashlib.md5(filestozip).hexdigest()[0:7]+".zip"
        if os.path.isfile(zipfile):
            return zipfile
        command  = "zip -@ %s" % zipfile
        process  = Popen(command,shell=True,stdin=-1)
        process.communicate(filestozip)
        process.wait()
        return zipfile
     
    zip.exposed = True 
    get.exposed = True
    #tag.exposed = True    
    save.exposed = True
    stats.exposed = True
    #deltag.exposed = True
cherrypy.quickstart(server(),'/',os.path.join(cproot,"cpconfig"))
